<?php

// 限时抢购商品

namespace app\console\model;

use think\Db;
use think\Model;

class Limited extends Model
{

    // 限时抢购 商品 关联
    public function ShopGoods()
    {
        return $this->hasOne('ShopGoods','id','goods_id')->field('id,price,title');
    }


    // 限时抢购商品 店铺 关联
    public function Shop()
    {
        return $this->belongsTo('Shop','member_id','member_id')->field('member_id,title');
    }


    // 模型事件
    protected static function init()
    {
        // 新增之前
        self::event('before_insert',function ($data){
            // 已购数量
            $data->purchase_number = 0;
            $data->parenTid = 2;
            // 创建时间
            $data->create_time = date('Y-m-d H:i:s',time());

        });


        // 写入之前
        self::event('before_write',function ($data){
            // 店铺ID
            $shopId = Db::name('ShopGoods')->where('id',$data->goods_id)->find();
            $data->member_id = $shopId['member_id'];
        });


        // 写入之后
        self::event('after_write',function ($data) {
            // 更新商品信息
            Db::name('ShopGoods')->where('id',$data->goods_id)->update(['activity'=>1]);
        });

        // 删除之前
        self::event('before_delete',function ($data) {

            Db::name('ShopGoods')->where('id',$data->goods_id)->update(['activity'=>2]);


        });
    }
}